package com.example.springboot_sdse_air.controller;

import cn.hutool.core.io.FileUtil;
import com.example.springboot_sdse_air.common.Result;
import com.example.springboot_sdse_air.entity.Pdf;
import com.example.springboot_sdse_air.service.PdfService;
import com.example.springboot_sdse_air.service.MinerULocalBatchService;
import com.example.springboot_sdse_air.service.ZipService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 功能：
 * 作者：王彬 202200111149
 * 日期：2025-04-26 15:37
 */
@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    @Resource
    PdfService pdfService;

    @Resource
    MinerULocalBatchService minerULocalBatchService;

    @Resource
    ZipService zipService;

    private static final String ROOT_PATH = System.getProperty("user.dir") + File.separator + "files";

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file,
                         @RequestParam("uid") Integer uid) throws IOException {
        String originalFilename = file.getOriginalFilename();  // 文件的原始名称

        String mainName = FileUtil.mainName(originalFilename);  // 文件名
        String extName = FileUtil.extName(originalFilename);  // 文件拓展名
        String save_path = ROOT_PATH + File.separator + "UserPdf" + File.separator + mainName; // 真正的存储父文件夹
        String parent_folder_name;
        if (!FileUtil.exist(save_path)) {
            FileUtil.mkdir(save_path);  // 如果当前文件的父级目录不存在，就创建
            parent_folder_name = mainName;
        } else {
            //后期可以加逻辑，判断文件的hash值
            long random = System.currentTimeMillis();
            save_path = save_path + "_" + random; // 如果当前文件的父级目录存在，说明冲突，需要重命名
            parent_folder_name = mainName + "_" + random;
            FileUtil.mkdir(save_path);
        }
        File saveFile = new File(save_path + File.separator + originalFilename);
        file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去
        String download_url = "http://" + ip + ":" + port + "/file/download/" + parent_folder_name + "/" + originalFilename;
        String preview_url = "http://" + ip + ":" + port + "/file/preview/" + parent_folder_name + "/" + originalFilename;
        // 同步保存数据库
        Pdf pdf = new Pdf();
        pdf.setName(originalFilename);
        pdf.setParentFolderName(parent_folder_name);
        pdf.setUid(uid);
        pdf.setDownloadUrl(download_url);
        pdf.setPreviewUrl(preview_url);
        pdf.setStatus("success"); // 设置文件状态为成功
        pdfService.save(pdf);
        
        // 上传成功后，调用MinerU进行PDF解析
        try {
            // 构建MinerU需要的参数
            Map<String, Object> uploadFile = new HashMap<>();
            uploadFile.put("filePath", saveFile.getAbsolutePath());
            uploadFile.put("fileName", originalFilename);
            List<Map<String, Object>> uploadFiles = new ArrayList<>();
            uploadFiles.add(uploadFile);
            
            // 调用MinerU进行PDF解析
            String batchId = minerULocalBatchService.getUrlsAndUploadFileBatch(uploadFiles);
            List<String> zipUrls = minerULocalBatchService.fetchExtractResultWithPolling(batchId);
            
            // 下载并解压结果文件
            for (String zipUrl : zipUrls) {
                File zipFile = zipService.downloadZip(zipUrl, pdf.getId());
                File destFolder = zipService.unzip(zipFile);
            }
            
            System.out.println("PDF解析完成: " + originalFilename);
        } catch (Exception e) {
            System.err.println("PDF解析失败: " + originalFilename + ", 错误: " + e.getMessage());
            // 解析失败不影响上传成功，只记录日志
        }
        return Result.success(preview_url);  //返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是我的后台提供出来的
    }

    @PostMapping("/uploadBatch")
    public Result uploadBatch(@RequestParam("files") MultipartFile[] files,
                              @RequestParam("uid") Integer uid) throws IOException {
        if (files.length == 0) {
            return Result.error("上传文件为空！");
        }
        List<String> urls = new ArrayList<>();
        List<Pdf> savedPdfs = new ArrayList<>();
        List<Map<String, Object>> uploadFiles = new ArrayList<>();
        
        // 先保存所有文件到本地和数据库
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();  // 文件的原始名称

            String mainName = FileUtil.mainName(originalFilename);  // 文件名
            String extName = FileUtil.extName(originalFilename);  // 文件拓展名
            String save_path = ROOT_PATH + File.separator + "UserPdf" + File.separator + mainName; // 真正的存储父文件夹
            String parent_folder_name;
            if (!FileUtil.exist(save_path)) {
                FileUtil.mkdir(save_path);  // 如果当前文件的父级目录不存在，就创建
                parent_folder_name = mainName;
            } else {
                //后期可以加逻辑，判断文件的hash值
                long random = System.currentTimeMillis();
                save_path = save_path + "_" + random; // 如果当前文件的父级目录存在，说明冲突，需要重命名
                parent_folder_name = mainName + "_" + random;
                FileUtil.mkdir(save_path);
            }
            File saveFile = new File(save_path + File.separator + originalFilename);
            file.transferTo(saveFile);  // 存储文件到本地的磁盘里面去
            String download_url = "http://" + ip + ":" + port + "/file/download/" + parent_folder_name + "/" + originalFilename;
            String preview_url = "http://" + ip + ":" + port + "/file/preview/" + parent_folder_name + "/" + originalFilename;

            // 同步保存数据库
            Pdf pdf = new Pdf();
            pdf.setName(originalFilename);
            pdf.setParentFolderName(parent_folder_name);
            pdf.setUid(uid);
            pdf.setDownloadUrl(download_url);
            pdf.setPreviewUrl(preview_url);
            pdf.setStatus("success"); // 设置文件状态为成功

            try {
                pdfService.save(pdf);
                savedPdfs.add(pdf);
                urls.add(preview_url);
                
                // 构建MinerU需要的参数
                Map<String, Object> uploadFile = new HashMap<>();
                uploadFile.put("filePath", saveFile.getAbsolutePath());
                uploadFile.put("fileName", originalFilename);
                uploadFiles.add(uploadFile);
                
            } catch (Exception e) {
                urls.add(null);
                return Result.error("系统错误：" + e.getMessage());
            }
        }

        // 批量调用MinerU进行PDF解析
        if (!uploadFiles.isEmpty()) {
            try {
                // 调用MinerU进行批量PDF解析
                String batchId = minerULocalBatchService.getUrlsAndUploadFileBatch(uploadFiles);
                List<String> zipUrls = minerULocalBatchService.fetchExtractResultWithPolling(batchId);
                
                // 下载并解压结果文件
                for (int i = 0; i < zipUrls.size() && i < savedPdfs.size(); i++) {
                    String zipUrl = zipUrls.get(i);
                    Pdf pdf = savedPdfs.get(i);
                    File zipFile = zipService.downloadZip(zipUrl, pdf.getId());
                    File destFolder = zipService.unzip(zipFile);
                }
                
                System.out.println("批量PDF解析完成，共处理 " + uploadFiles.size() + " 个文件");
            } catch (Exception e) {
                System.err.println("批量PDF解析失败，错误: " + e.getMessage());
                // 解析失败不影响上传成功，只记录日志
            }
        }

        return Result.success(urls);  //返回文件的链接，这个链接就是文件的下载地址，这个下载地址就是我的后台提供出来的
    }

    @GetMapping("/download/{parentFolderName}/{fileName:.+}")
    public void download(@PathVariable String parentFolderName,
                         @PathVariable String fileName,
                         HttpServletRequest request,
                         HttpServletResponse response) throws IOException {
        // 首先尝试普通PDF文件路径
        String filePath = ROOT_PATH + File.separator + "UserPdf" + File.separator + parentFolderName + File.separator + fileName;
        File file = new File(filePath);
        
        // 如果普通路径不存在，尝试SystemPdf路径
        if (!file.exists()) {
            filePath = ROOT_PATH + File.separator + "SystemPdf" + File.separator + parentFolderName + File.separator + fileName;
            file = new File(filePath);
        }

        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("文件不存在！");
            return;
        }

        // 设置响应头，开始下载
        response.setContentType("application/octet-stream");
        
        // 处理中文文件名编码
        String encodedFileName = java.net.URLEncoder.encode(file.getName(), "UTF-8");
        // 将编码后的文件名中的+号替换为%20，确保兼容性
        encodedFileName = encodedFileName.replace("+", "%20");
        
        // 设置Content-Disposition头，支持中文文件名
        String userAgent = request.getHeader("User-Agent");
        if (userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge"))) {
            // IE浏览器
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
        } else {
            // 其他浏览器
            response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
        }

        try (FileInputStream fis = new FileInputStream(file);
             ServletOutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        }
    }

    @GetMapping("/preview/{parentFolderName}/{fileName:.+}")
    public void previewPdf(@PathVariable String parentFolderName,
                           @PathVariable String fileName,
                           HttpServletResponse response) throws IOException {
        // 首先尝试普通PDF文件路径
        String filePath = ROOT_PATH + File.separator + "UserPdf" + File.separator + parentFolderName + File.separator + fileName;
        File file = new File(filePath);
        
        // 如果普通路径不存在，尝试SystemPdf路径
        if (!file.exists()) {
            filePath = ROOT_PATH + File.separator + "SystemPdf" + File.separator + parentFolderName + File.separator + fileName;
            file = new File(filePath);
        }

        if (!file.exists()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("文件不存在！");
            return;
        }

        response.setContentType("application/pdf");  // 关键！！设置成 PDF 类型！
        try (FileInputStream fis = new FileInputStream(file);
             ServletOutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            os.flush();
        }
    }


    @GetMapping("/downloadZip/{folderName}")
    public void downloadZip(@PathVariable String folderName, HttpServletResponse response) throws IOException {
        String folderPath = ROOT_PATH + File.separator + folderName;
        File folder = new File(folderPath);
        if (!folder.exists() || !folder.isDirectory()) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.getWriter().write("文件夹不存在！");
            return;
        }

        // 设置响应头
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + folderName + ".zip\"");

        // 把文件夹打包成zip写到响应流
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            zipFolder(folder, folder.getName(), zos);
            zos.flush();
        }
    }

    /**
     * 获取Markdown文件内容
     */
    @GetMapping("/getMarkdownContent")
    public Result getMarkdownContent(@RequestParam Integer fileId) {
        try {
            // 根据文件ID获取PDF文件信息
            Pdf pdf = pdfService.getById(fileId);
            if (pdf == null) {
                return Result.error("PDF文件不存在");
            }
            
            // 构建Markdown文件路径
            // PDF文件路径: files/UserPdf/{parentFolderName}/{fileName}
            // Markdown文件路径: files/UserPdf/{parentFolderName}/{fileNameWithoutExt}/markdown.md
            String fileName = pdf.getName();
            String fileNameWithoutExt = fileName.replaceAll("\\.pdf$", "");
            String markdownPath = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                                + pdf.getParentFolderName() + File.separator 
                                + fileNameWithoutExt + File.separator + fileNameWithoutExt + ".md";
            
            File markdownFile = new File(markdownPath);
            
            if (!markdownFile.exists()) {
                return Result.error("Markdown文件不存在");
            }
            
            // 读取文件内容
            String content = cn.hutool.core.io.FileUtil.readUtf8String(markdownFile);
            return Result.success(content);
        } catch (Exception e) {
            return Result.error("读取Markdown文件失败: " + e.getMessage());
        }
    }

    /**
     * 图片预览接口
     * 根据fileId和imageName返回图片文件
     */
    @GetMapping("/previewImage")
    public void previewImage(@RequestParam Integer fileId,
                            @RequestParam String imageName,
                            HttpServletResponse response) throws IOException {
        try {
            // 根据文件ID获取PDF文件信息
            Pdf pdf = pdfService.getById(fileId);
            if (pdf == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("PDF文件不存在");
                return;
            }
            
            // 构建图片文件路径
            // PDF文件路径: files/UserPdf/{parentFolderName}/{fileName}
            // 图片文件路径: files/UserPdf/{parentFolderName}/{fileNameWithoutExt}/images/{imageName}
            String fileName = pdf.getName();
            String fileNameWithoutExt = fileName.replaceAll("\\.pdf$", "");
            String imagePath = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                             + pdf.getParentFolderName() + File.separator 
                             + fileNameWithoutExt + File.separator + "images" + File.separator + imageName;
            
            File imageFile = new File(imagePath);
            
            if (!imageFile.exists()) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("图片文件不存在: " + imageName);
                return;
            }
            
            // 根据文件扩展名设置Content-Type
            String contentType = getImageContentType(imageName);
            response.setContentType(contentType);
            
            // 设置缓存头，提高性能
            response.setHeader("Cache-Control", "public, max-age=31536000"); // 缓存1年
            response.setHeader("ETag", "\"" + imageFile.lastModified() + "\"");
            
            // 返回图片文件流
            try (FileInputStream fis = new FileInputStream(imageFile);
                 ServletOutputStream os = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
                os.flush();
            }
            
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("图片加载失败: " + e.getMessage());
        }
    }
    
    /**
     * 根据文件扩展名获取图片的Content-Type
     */
    private String getImageContentType(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        switch (extension) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "bmp":
                return "image/bmp";
            case "webp":
                return "image/webp";
            case "svg":
                return "image/svg+xml";
            default:
                return "application/octet-stream";
        }
    }

    /**
     * 上传图片到指定文件的images目录
     * 用于测试图片预览功能
     */
    @PostMapping("/uploadImage")
    public Result uploadImage(@RequestParam("file") MultipartFile file,
                             @RequestParam("fileId") Integer fileId) throws IOException {
        try {
            // 根据文件ID获取PDF文件信息
            Pdf pdf = pdfService.getById(fileId);
            if (pdf == null) {
                return Result.error("PDF文件不存在");
            }
            
            // 构建图片存储路径
            String fileName = pdf.getName();
            String fileNameWithoutExt = fileName.replaceAll("\\.pdf$", "");
            String imagesDir = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                             + pdf.getParentFolderName() + File.separator 
                             + fileNameWithoutExt + File.separator + "images";
            
            // 创建images目录
            File imagesFolder = new File(imagesDir);
            if (!imagesFolder.exists()) {
                imagesFolder.mkdirs();
            }
            
            // 保存图片文件
            String originalFilename = file.getOriginalFilename();
            File imageFile = new File(imagesDir + File.separator + originalFilename);
            file.transferTo(imageFile);
            
            // 构建图片访问URL
            String imageUrl = "http://" + ip + ":" + port + "/file/previewImage?fileId=" + fileId + "&imageName=" + originalFilename;
            
            return Result.success(imageUrl);
        } catch (Exception e) {
            return Result.error("图片上传失败: " + e.getMessage());
        }
    }

    // 递归打包文件夹的方法
    private void zipFolder(File folder, String basePath, ZipOutputStream zos) throws IOException {
        File[] files = folder.listFiles();
        if (files == null) return;

        for (File file : files) {
            if (file.isDirectory()) {
                zipFolder(file, basePath + "/" + file.getName(), zos);
            } else {
                try (FileInputStream fis = new FileInputStream(file)) {
                    ZipEntry entry = new ZipEntry(basePath + "/" + file.getName());
                    zos.putNextEntry(entry);
                    byte[] buffer = new byte[1024];
                    int len;
                    while ((len = fis.read(buffer)) != -1) {
                        zos.write(buffer, 0, len);
                    }
                    zos.closeEntry();
                }
            }
        }
    }

    /**
     * 打包下载整个论文内容（PDF、Markdown、图片等）
     */
    @GetMapping("/downloadPaper/{fileId}")
    public void downloadPaper(@PathVariable Integer fileId, 
                             HttpServletRequest request,
                             HttpServletResponse response) throws IOException {
        try {
            System.out.println("=== 开始下载论文包 ===");
            System.out.println("文件ID: " + fileId);
            
            // 根据fileId获取PDF文件信息
            Pdf pdf = pdfService.getById(fileId);
            if (pdf == null) {
                System.out.println("❌ PDF文件不存在，ID: " + fileId);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                response.getWriter().write("PDF文件不存在！");
                return;
            }

            System.out.println("✅ 找到PDF文件: " + pdf.getName());
            System.out.println("父文件夹名: " + pdf.getParentFolderName());

            // 构建文件路径
            String fileName = pdf.getName();
            String fileNameWithoutExt = fileName.replaceAll("\\.pdf$", "");
            String pdfPath = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                           + pdf.getParentFolderName() + File.separator + fileName;
            String markdownPath = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                                + pdf.getParentFolderName() + File.separator 
                                + fileNameWithoutExt + File.separator + fileNameWithoutExt + ".md";
            String imagesPath = ROOT_PATH + File.separator + "UserPdf" + File.separator 
                              + pdf.getParentFolderName() + File.separator 
                              + fileNameWithoutExt + File.separator + "images";

            System.out.println("PDF路径: " + pdfPath);
            System.out.println("Markdown路径: " + markdownPath);
            System.out.println("图片路径: " + imagesPath);

            // 检查文件是否存在
            File pdfFile = new File(pdfPath);
            File markdownFile = new File(markdownPath);
            File imagesFolder = new File(imagesPath);

            System.out.println("PDF文件存在: " + pdfFile.exists());
            System.out.println("Markdown文件存在: " + markdownFile.exists());
            System.out.println("图片文件夹存在: " + imagesFolder.exists());

            // 设置响应头
            String zipFileName = fileNameWithoutExt + "_完整论文.zip";
            String encodedFileName = java.net.URLEncoder.encode(zipFileName, "UTF-8");
            encodedFileName = encodedFileName.replace("+", "%20");
            
            response.setContentType("application/zip");
            String userAgent = request.getHeader("User-Agent");
            if (userAgent != null && (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge"))) {
                response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            } else {
                response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
            }

            System.out.println("开始创建ZIP文件: " + zipFileName);

            // 创建ZIP输出流
            try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
                
                // 1. 添加PDF文件
                if (pdfFile.exists()) {
                    System.out.println("✅ 添加PDF文件到ZIP");
                    addFileToZip(zos, pdfFile, fileName, "PDF文件");
                } else {
                    System.out.println("❌ PDF文件不存在: " + pdfPath);
                }

                // 2. 添加Markdown文件
                if (markdownFile.exists()) {
                    System.out.println("✅ 添加Markdown文件到ZIP");
                    addFileToZip(zos, markdownFile, "markdown.md", "Markdown提取文件");
                } else {
                    System.out.println("❌ Markdown文件不存在: " + markdownPath);
                }

                // 3. 添加图片文件夹
                if (imagesFolder.exists() && imagesFolder.isDirectory()) {
                    System.out.println("✅ 添加图片文件夹到ZIP");
                    addFolderToZip(zos, imagesFolder, "images", "图片文件");
                } else {
                    System.out.println("❌ 图片文件夹不存在: " + imagesPath);
                }

                // 4. 添加README文件
                System.out.println("✅ 添加README文件到ZIP");
                addReadmeToZip(zos, pdf, fileNameWithoutExt);

                zos.flush();
                System.out.println("✅ ZIP文件创建完成");
            }

        } catch (Exception e) {
            System.err.println("❌ 下载失败: " + e.getMessage());
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("下载失败：" + e.getMessage());
        }
    }

    /**
     * 添加文件到ZIP
     */
    private void addFileToZip(ZipOutputStream zos, File file, String entryName, String description) throws IOException {
        ZipEntry entry = new ZipEntry(entryName);
        entry.setComment(description);
        zos.putNextEntry(entry);
        
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
        }
        zos.closeEntry();
    }

    /**
     * 添加文件夹到ZIP
     */
    private void addFolderToZip(ZipOutputStream zos, File folder, String entryName, String description) throws IOException {
        File[] files = folder.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isFile()) {
                    String relativePath = entryName + File.separator + file.getName();
                    addFileToZip(zos, file, relativePath, "图片文件");
                }
            }
        }
    }

    /**
     * 添加README文件到ZIP
     */
    private void addReadmeToZip(ZipOutputStream zos, Pdf pdf, String fileNameWithoutExt) throws IOException {
        String readmeContent = String.format(
            "# %s - 完整论文包\n\n" +
            "## 文件说明\n\n" +
            "本压缩包包含以下文件：\n\n" +
            "### 1. PDF文件\n" +
            "- **文件名**: %s\n" +
            "- **说明**: 原始PDF论文文件\n\n" +
            "### 2. Markdown文件\n" +
            "- **文件名**: markdown.md\n" +
            "- **说明**: 从PDF中提取的Markdown格式内容\n\n" +
            "### 3. 图片文件夹\n" +
            "- **文件夹**: images/\n" +
            "- **说明**: 从PDF中提取的图片文件\n\n" +
            "## 使用说明\n\n" +
            "1. 解压后可以直接查看PDF文件\n" +
            "2. markdown.md文件可以用任何Markdown编辑器打开\n" +
            "3. images文件夹包含论文中的所有图片\n\n" +
            "## 生成信息\n\n" +
            "- **生成时间**: %s\n" +
            "- **文件ID**: %d\n" +
            "- **原始文件名**: %s\n\n" +
            "---\n" +
            "*此文件由SDSE AIR系统自动生成*",
            fileNameWithoutExt,
            pdf.getName(),
            new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()),
            pdf.getId(),
            pdf.getName()
        );

        ZipEntry entry = new ZipEntry("README.md");
        entry.setComment("说明文件");
        zos.putNextEntry(entry);
        zos.write(readmeContent.getBytes("UTF-8"));
        zos.closeEntry();
    }
}
